package com.ys.utils.mobao;

import com.alibaba.fastjson.JSON;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.util.EntityUtils;
import sun.net.www.protocol.http.HttpURLConnection;

import javax.net.ssl.*;
import java.io.ByteArrayOutputStream;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.net.URLConnection;
import java.security.GeneralSecurityException;
import java.security.cert.X509Certificate;
import java.util.List;


public class Mobo360Merchant {

	private Mobo360Merchant() {

	}

	/**
	 * 发送请求到支付网关并接受回复
	 * 
	 * @param paramsStr
	 *            请求参数字符串
	 * @param serverUrl
	 *            支付网关地址
	 * @return
	 * @throws Exception
	 */
	public static String transact(String paramsStr, String serverUrl)
			throws Exception {

		if (StringUtils.isBlank(serverUrl) || StringUtils.isBlank(paramsStr)) {
			throw new NullPointerException("请求地址或请求数据为空!");
		}
//		System.out.println("------------" + paramsStr);
		myX509TrustManager xtm = new myX509TrustManager();
		myHostnameVerifier hnv = new myHostnameVerifier();
		ByteArrayOutputStream respData = new ByteArrayOutputStream();

		byte[] b = new byte[8192];
		String result = "";
		try {
			SSLContext sslContext = null;
			try {
				sslContext = SSLContext.getInstance("TLS");
				X509TrustManager[] xtmArray = new X509TrustManager[] { xtm };
				sslContext.init(null, xtmArray,
						new java.security.SecureRandom());
			} catch (GeneralSecurityException e) {
				e.printStackTrace();
			}

			if (sslContext != null) {
				HttpsURLConnection.setDefaultSSLSocketFactory(sslContext
						.getSocketFactory());
			}
			HttpsURLConnection.setDefaultHostnameVerifier(hnv);

			// 匹配http或者https请求
			URLConnection conn = null;
			if (serverUrl.toLowerCase().startsWith("https")) {
				HttpsURLConnection httpsUrlConn = (HttpsURLConnection) (new URL(
						serverUrl)).openConnection();
				httpsUrlConn.setRequestMethod("POST");
				conn = httpsUrlConn;
			} else {
				HttpURLConnection httpUrlConn = (HttpURLConnection) (new URL(
						serverUrl)).openConnection();
				httpUrlConn.setRequestMethod("POST");
				conn = httpUrlConn;
			}

			conn.setConnectTimeout(5000);
			conn.setReadTimeout(30000);
			conn
					.setRequestProperty(
							"User-Agent",
							"Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.8.1.1) Gecko/20061204 Firefox/2.0.0.3");
			conn.setRequestProperty("Content-Type",
					"application/x-www-form-urlencoded");
			conn.setRequestProperty("connection", "close");
			conn.setDoOutput(true);
			conn.setDoInput(true);
			conn.getOutputStream().write(paramsStr.getBytes("utf-8"));
			conn.getOutputStream().flush();

			int len = 0;
			try {
				while (true) {
					len = conn.getInputStream().read(b);
					if (len <= 0) {
						conn.getInputStream().close();
						break;
					}
					respData.write(b, 0, len);
				}
			} catch (SocketTimeoutException ee) {
				throw new RuntimeException("读取响应数据出错！" + ee.getMessage());
			}

			// 返回给商户的数据
			result = respData.toString("utf-8");
			if (StringUtils.isBlank(result)) {
				throw new RuntimeException("返回参数错误！");
			}
		} catch (Exception e) {
			throw new RuntimeException("发送POST请求出现异常！" + e.getMessage());
		}

		// 验签返回数据后返回支付平台回复数据
//		checkResult(result);
		return result;
	}

	public static String post(String server, List<NameValuePair> paramList) throws Exception {

		System.out.println("url: " + server + " data: " + JSON.toJSONString(paramList));
		URL url = new URL(server);
		DefaultHttpClient httpclient = new DefaultHttpClient();
		HttpPost httpPost = new HttpPost(url.toURI());
		httpclient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 5000);
		httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 60000);

		if (paramList != null) {
			httpPost.setEntity(new UrlEncodedFormEntity(paramList, "UTF-8"));
		}

		HttpResponse response = httpclient.execute(httpPost);
		if (response.getStatusLine().getStatusCode() != 200) {
			throw new Exception("HTTP请求异常:" + response.getStatusLine().getStatusCode());
		}
		String rst = EntityUtils.toString(response.getEntity(), "UTF-8");
		System.out.println("url: " + server + "response: " + rst);
		return rst;
	}





}

class myX509TrustManager implements X509TrustManager {
@Override
	public void checkClientTrusted(X509Certificate[] chain, String authType) {
	}
	@Override
	public void checkServerTrusted(X509Certificate[] chain, String authType) {
	}
	@Override
	public X509Certificate[] getAcceptedIssuers() {
		return null;
	}
}

class myHostnameVerifier implements HostnameVerifier {
	@Override
	public boolean verify(String hostname, SSLSession session) {
		return true;
	}

}